package natappvip.liujinliang.controller;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class FileUpLoadController {

	@Value("${uploadPath}")
	private String path;
	
	@Autowired
	private CommonsMultipartResolver fileResolver;

	@RequestMapping("/upload")
	public String upload() {
		return "fileUpload";
	}

	/**
	 * 这里涉及到元素绑定，将我们页面传过来的表单数据绑定到我们的参数对象上面
	 * 具体的来说，需要使用@RequestParam请求参数来实现绑定过程，并且会 自动的将表单数据转换为 MultipartFile
	 * 类型，这个过程不用我们实现
	 * 
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
	public String doUpload(MultipartFile file) throws IOException {

		/** 直接使用 MultipartFile 接口 将文件 拷贝到指定的位置 */
		if (!file.isEmpty()) {
			FileUtils.copyInputStreamToFile(
					file.getInputStream(),
					new File(path, System.currentTimeMillis()
							+ file.getOriginalFilename()));
		}

		return "success";
	}
}
